﻿component
{
	/*用户操作模块*/
	include "../../inc/lib.cfm";
	//列表操作
	public any function list(any rc)
	{
		var result = {};
		//从对象中进行Hql模式查询
		var offset = (rc.page-1)*rc.rows;
		hql = "from user where " & rc.sqlWhere & rc.sqlSort;

		var result["rows"] = ormExecuteQuery(hql, false, {maxResults=rc.rows, offset=offset});
		var totalhql = "select count(id) as total from user where " & rc.sqlWhere ;
		var result["total"] = ormExecuteQuery(totalhql, true);

		//格式化日期、性别等操作
		for(i = 1; i <= arraylen(result.rows); i++)
		{
			result.rows[i].setSex( result.rows[i].getSexName() );
		}
		//返回数据
		return result;
	}

	//用户角色树对象
	public any function getRoleGrantTree(numeric id){
		//从组织资源对应对象中获取传递过来的指定ID的数据内容
		var hql = "from userrole where userid =" & arguments.id;
		var result = ormExecuteQuery(hql,false);

		//将资源ID组成idList字符串内容
		idList="";
		for(var i = 1;i<= arraylen(result);i++){
			idList = listAppend(idList,result[i].getRoleid().getId());
		}

		//只获取idList的节点内容
		var checkRole = [];
		for(var i=1;i<=listlen(idList);i++){
			checkRole[i] = getRoleById( listgetat(idList,i) );
			checkRole[i]['text'] = checkRole[i].getName();
		}
		return checkRole;

	}

	public any function	getRoleById(numeric id){
		result = entityLoadByPk("role", arguments.id);
		return result;
	}


	//用户组织树对象
	public any function getOrganizationGrantTree(numeric id){
		//从组织资源对应对象中获取传递过来的指定ID的数据内容
		var hql = "from userorganization where userid =" & arguments.id;
		var result = ormExecuteQuery(hql,false);

		//将资源ID组成idList字符串内容
		idList="";
		for(var i = 1;i<= arraylen(result);i++){
			idList = listAppend(idList,result[i].getOrganizationid().getId());
		}

		//只获取idList的节点内容
		var checkOrganization = [];
		for(var i=1;i<=listlen(idList);i++){
			checkOrganization[i] = getOrganizationById( listgetat(idList,i) );
		}
		return checkOrganization;

	}

	public any function	getOrganizationById(numeric id){
		result = entityLoadByPk("organization", arguments.id);
		return result;
	}



	//删除操作
	public any function delete(numeric id){
		transaction {
            var user = entityLoadByPk("user", arguments.id);
           	entityDelete(user);
            transactionCommit();
        }
	}

	//获取操作
	public any function get(numeric id){
		result = entityLoadByPk("user", arguments.id);
		return result;
	}

	//新增操作
	public any function save(any rc){
		transaction {
            var q = entityNew("user");
			include "../../inc/saveandupdatenotcommit.cfm";
			q.setPwd(hash(q.getPwd()));
			entitySave(q);
			transactionCommit();
        }
        return q;
	}

	//修改操作
	public any function update(any rc){
		transaction {
            var q = entityLoadByPk("user", rc.id);
            var pwd = q.getpwd();
			include "../../inc/saveandupdatenotcommit.cfm";
			if(pwd != rc.pwd){
				q.setPwd( hash( rc.pwd ) );
			}
			entitySave(q);
			transactionCommit();
        }
        return q;
	}

	public any function getUserRole(numeric id){
		var result = {};
		var hql = "from userrole where userid = " & id;
		var result = ormExecuteQuery(hql,false);
		return result;
	}

	//授权操作
	public any function saveRoleGrant(any rc){
		transaction {
			//在授权之前，先要检查ids是否已经存在在userrole中
			/*
			ids需要分成三部分
			1.需要新添加的
			2.不需要操作的
			3.要删除操作的

			示例如下：
			ids1 = "1,2,3,4,5"; //新传递进来的值
			ids2 = "1,3,8,9";	//原来已经存在的值
			writeoutput(":" & listCompare(ids1,ids2));
			writeoutput("不需要操作的:" & ListInCommon(ids1,ids2));
			writeoutput("要删除操作的:" & listdelete(ListInCommon(ids1,ids2),ids2));
			需要新添加的:2,4,5
			不需要操作的:1,3
			要删除操作的:8,9
			*/
			var orObj = getUserRole(rc.id);
			oldIds = "";
			checkIds = "";

			for(var i=1;i<=arraylen(orObj);i++){
				oldIds = listAppend(oldIds,orObj[i].getRoleid().getId());
				checkIds = listAppend(checkIds,orObj[i].getId());
			}

			needInsertIds = listCompare(rc.ids,oldIds);
			keepStatusIds = ListInCommon(rc.ids,oldIds);
			needDeleteIds = listdelete(ListInCommon(rc.ids,oldIds),oldIds);

			//writeoutput("1:" & needInsertIds & "--2:" & keepStatusIds & "--3:" & needDeleteIds);
			//需要删除的部分
            if(listlen(needDeleteIds)){
				for(var i=1;i<=listlen(needDeleteIds);i++){
					var deleteId =  listgetat(checkIds, listfindnocase( oldIds,listgetat(needDeleteIds,i) )) ;
					var orEntity = entityLoadByPk("userrole", deleteId);
					entityDelete(orEntity);
				}
			}

			//需要添加的部分
			if(listlen(needInsertIds)){
				for(var i=1;i<=listlen(needInsertIds);i++){
					var q = entityNew("userrole");
					//建立role实体，进行赋值
					var r = entityNew("role");
					r.setid(listgetat(needInsertIds,i));
					//建立user实体，进行赋值
					var o = entityNew("user");
					o.setId(rc.id);
					//将对象存储至userrole实体中去
					q.setRoleid(r);
					q.setUserid(o);
					entitySave(q);
				}
            }

            transactionCommit();
        }
        return true;
	}

	public any function getUserOrganization(numeric id){
		var result = {};
		var hql = "from userorganization where userid = " & id;
		var result = ormExecuteQuery(hql,false);
		return result;
	}

	//授权操作
	public any function saveOrganizationGrant(any rc){
		transaction {
			//在授权之前，先要检查ids是否已经存在在userorganization中
			/*
			ids需要分成三部分
			1.需要新添加的
			2.不需要操作的
			3.要删除操作的

			示例如下：
			ids1 = "1,2,3,4,5"; //新传递进来的值
			ids2 = "1,3,8,9";	//原来已经存在的值
			writeoutput(":" & listCompare(ids1,ids2));
			writeoutput("不需要操作的:" & ListInCommon(ids1,ids2));
			writeoutput("要删除操作的:" & listdelete(ListInCommon(ids1,ids2),ids2));
			需要新添加的:2,4,5
			不需要操作的:1,3
			要删除操作的:8,9
			*/
			var orObj = getUserOrganization(rc.id);
			oldIds = "";
			checkIds = "";

			for(var i=1;i<=arraylen(orObj);i++){
				oldIds = listAppend(oldIds,orObj[i].getOrganizationid().getId());
				checkIds = listAppend(checkIds,orObj[i].getId());
			}

			needInsertIds = listCompare(rc.ids,oldIds);
			keepStatusIds = ListInCommon(rc.ids,oldIds);
			needDeleteIds = listdelete(ListInCommon(rc.ids,oldIds),oldIds);

			//writeoutput("1:" & needInsertIds & "--2:" & keepStatusIds & "--3:" & needDeleteIds);
			//需要删除的部分
            if(listlen(needDeleteIds)){
				for(var i=1;i<=listlen(needDeleteIds);i++){
					var deleteId =  listgetat(checkIds, listfindnocase( oldIds,listgetat(needDeleteIds,i) )) ;
					var orEntity = entityLoadByPk("userorganization", deleteId);
					entityDelete(orEntity);
				}
			}

			//需要添加的部分
			if(listlen(needInsertIds)){
				for(var i=1;i<=listlen(needInsertIds);i++){
					var q = entityNew("userorganization");
					//建立organization实体，进行赋值
					var r = entityNew("organization");
					r.setid(listgetat(needInsertIds,i));
					//建立user实体，进行赋值
					var o = entityNew("user");
					o.setId(rc.id);
					//将对象存储至userorganization实体中去
					q.setOrganizationid(r);
					q.setUserid(o);
					entitySave(q);
				}
            }

            transactionCommit();
        }
        return true;
	}


	public any function login(any rc){
        var user = entityLoad("user", {loginname=#rc.loginname#, pwd=#hash(rc.pwd)#},true);
        if(!isNull(user)) {
        	userid = user.getId();
        	//用户组织机构
        	var resultUserOrganization = {};
			var hqlUserOrganization = "from userorganization where userid = " & userid;
			var resultUserOrganization = ormExecuteQuery(hqlUserOrganization,false);

			allRsAuths = [];
			//获取具体的组织机构
			for(var i = 1; i <= arraylen(resultUserOrganization); i++){
				singleRsAuths = [];

				var resultOrganization = {};
				var hqlOrganization = "from organizationresource where organizationid = " & resultUserOrganization[i].getOrganizationid().getId();
				var resultOrganization = ormExecuteQuery(hqlOrganization,false);


				for(var j = 1 ; j<= arraylen(resultOrganization); j++){
					var rsAuth={};
					rsAuth["resourceid"] = resultOrganization[j].getResourceid().getId();
					rsAuth["resourcetext"] = resultOrganization[j].getResourceid().getText();
					rsAuth["resourcetypeid"] = resultOrganization[j].getResourceid().getResourcetype().getId();
					rsAuth["checkurl"] = resultOrganization[j].getResourceid().getUrl();
					singleRsAuths[j] = rsAuth;
				}
				//将单个的资源内容进行合并，合并到AllRsAuths里去

				allRsAuths=arraymerge(allRsAuths,singleRsAuths);

			}


			//用户角色
        	var resultUserRole = {};
			var hqlUserRole = "from userrole where userid = " & userid;
			var resultUserRole = ormExecuteQuery(hqlUserRole,false);


        	for(var i = 1; i <= arraylen(resultUserRole); i++){
				singleRsAuths = [];

				var resultRole = {};
				var hqlRole = "from roleresource where roleid = " & resultUserRole[i].getRoleid().getId();
				var resultRole = ormExecuteQuery(hqlRole,false);


				for(var j = 1 ; j<= arraylen(resultRole); j++){
					var rsAuth={};
					rsAuth["resourceid"] = resultRole[j].getResourceid().getId();
					rsAuth["resourcetext"] = resultRole[j].getResourceid().getText();
					rsAuth["resourcetypeid"] = resultRole[j].getResourceid().getResourcetype().getId();
					rsAuth["checkurl"] = resultRole[j].getResourceid().getUrl();
					singleRsAuths[j] = rsAuth;
				}

				//将单个的资源内容进行合并，合并到AllRsAuths里去
				allRsAuths=arraymerge(allRsAuths,singleRsAuths);
			}

			//删除数据中重复的结构内容
			var resultRsAuths = [];
			for( var i=1; i<=arrayLen(allRsAuths); i++){
				var rsAuth={};
				for( var x=i+1; x<=arrayLen(allRsAuths); x++){
					if( allRsAuths[x].resourceid == allRsAuths[i].resourceid ) {
						arrayDeleteAt(allRsAuths,x);
						--x;
					}
				}

				rsAuth["resourceid"] = allRsAuths[i].resourceid;
				rsAuth["resourcetext"] = allRsAuths[i].resourcetext;
				rsAuth["resourcetypeid"] = allRsAuths[i].resourcetypeid;
				if(!isNull(allRsAuths[i].checkurl)){
					rsAuth["checkurl"] =allRsAuths[i].checkurl;
				}
				arrayAppend(resultRsAuths,rsAuth);
			}

            session.auth.userid = user.getId();
            session.auth.username = user.getName();
            session.auth.allRsAuths = resultRsAuths;

            return user;
        }

	}

	public any function getOrgRoleUser(any rc){
		//从userorganization取组织机构中的用户
		//从userrole取用户角色中的用户

		var resultOrg = {};
		var hqlOrg = "from userorganization where organizationid in (#rc.organizationids#)";
		var resultOrg = ormExecuteQuery(hqlOrg,false);

		var arrOrgIds = arrayNew();
		for(i = 1; i <= arraylen(resultOrg); i++)
		{
			arrayappend(arrOrgIds,resultOrg[i].getId());
		}

		var resultRole = {};
		var hqlRole = "from userrole where roleid in (#rc.roleids#)";
		var resultRole = ormExecuteQuery(hqlRole,false);

		var arrRoleIds = arrayNew();
		for(i = 1; i <= arraylen(resultRole); i++)
		{
			arrayappend(arrRoleIds,resultRole[i].getId());
		}

		var arrUserIds = listtoarray(rc.userids);
		var arrResult = arraymerge(arraymerge(arrUserIds,arrOrgIds),arrRoleIds);
		lstIds = ListDeleteDuplicatesNoCase( arraytolist(arrResult) );
		if( listfindnocase(lstIds,0) > 0){
			lstIds = listdeleteat(lstIds, listfindnocase(lstIds,0) );
		}

		lstIds = ListRemoveByString (lstIds,session.auth.userid);

		return lstIds;
	}

	public any function getUserCount(){
		var totalhql = "select count(id) as total from user" ;
		var result= ormExecuteQuery(totalhql, true);
		return result;
	}
}